import { useEffect, useMemo, useState } from 'react'
import { Dimensions } from 'react-native'

const { width, height } = Dimensions.get('window');

// // 设计基准尺寸（例如，iPhone X）
const designWidth = 375
const designHeight = height

// 自定义钩子，返回响应式尺寸计算函数
function useResponsive() {
  // 获取屏幕尺寸
  const [screenDimensions, setScreenDimensions] = useState(
    Dimensions.get('window')
  )

  // 计算字体大小的函数
  const fs = useMemo(() => {
    return (baseSize: number) => {
      const scale = screenDimensions.width / designWidth
      return baseSize * scale
    }
  }, [screenDimensions.width])

  const h = useMemo(() => {
    return (value: number) => {
      const { height } = screenDimensions
      return (value * height) / designHeight
    }
  }, [screenDimensions.height])

  const w = useMemo(() => {
    return (value: number) => {
      const { width } = screenDimensions
      return (value * width) / designWidth
    }
  }, [screenDimensions.width])

  useEffect(() => {
    // 监听屏幕变化
    const subscription = Dimensions.addEventListener('change', ({ window }) => {
      setScreenDimensions(window) // 更新状态以触发重新渲染
    })

    // 组件卸载时移除监听器
    return () => subscription.remove()
  }, [])

  return { h, w, fs }
}

export default useResponsive
